<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Models\Resource;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ResourceService
{
    public function get($search,$type = 'safe'){
        $sql = Resource::when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('title','like', '%'.$search.'%');
            });
        })->when($type, function ($query, $type) {
            return $query->where(function($query) use ($type) {
                $query->where('type',$type);
            });
        });

        return $sql;
    }

    public function insert($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        try {
            $res['user_id'] = Auth::user()->id;
            $data = Resource::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th->getMessage()));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            $v = $v === null ? '/' : $v;
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $res['user_id'] = Auth::user()->id;
            $data = Resource::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
}